<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
		<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=sSelQoVi2L3KofLo1HOobonW"></script>
		<title>获取地区轮廓线</title>
	</head>
	<style type="text/css">
		* {
			padding: 0;
			margin: 0;
			list-style: none;
		}

		.initial {
			width: 1000px;
		}

		.H {
			width: 100%;
			height: 20px;
			font-size: 12px;
			color: red;
			overflow: hidden;
		}

		.S {
			width: 1000px;
		}

		.C {
			width: 50px;
			height: 20px;
			font-size: 12px;
			color: red;
			font-weight: bold;
			background: rgb(210, 196, 196);
			float: left;
			border: 1px solid white;
			line-height: 20px;
			text-align: center;
			cursor: pointer;
		}
	</style>
	<body>
		<div id="main">
			<button type="button" id="btn">获取城市列表</button>
			<div class="initial"></div>
		</div>
		<div id="map" style="width:100%;height:800px"></div>
		<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
		<script type="text/javascript">
			function getBoundary() {
				$("#btn").click(function() {
					$.ajax({
						type: 'get',
						url: 'city.json', //城市json路径
						dataType: 'json',
						success: function(data) {
							for (k in data.city) {
								var H = $("<h2 class = 'H'>" + data.city[k].title + "</h2>"); //将获取到的首字母渲染到创建的H2里
								$(".initial").append(H); //将H2添加到名为initial的div父元素内
								var S = $("<ul class='S'></ul>"); //创建ul标签
								$(".initial").append(S); //将ul添加到名为initial的div父元素内
								for (var kk = 0; kk < data.city[k].lists.length; kk++) {
									var C = $("<li class = 'C'>" + data.city[k].lists[kk] + "</li>"); //获取每个首字母下对应的城市名称,并添加到创建的li中
									$(".S").eq(k).append(C); //将所创建的li添加到对应首字母的ul中去
								}
							}
							$("li").click(function() {
								console.log($(this).text());
								name = $(this).text(); //获取到所点击li的文本内容,存放在name里
								console.log(name);

								//-----华丽分界线（下面是获取城市轮廓图的代码）-----
								var map = new BMap.Map("map");
								map.enableScrollWheelZoom();
								// function getBoundary() {
								var bdary = new BMap.Boundary();
								// var name = '北京'; //**在这里直接输入城市名字即可**
								bdary.get(name, function(rs) { //获取行政区域
									map.clearOverlays(); //清除地图覆盖物
									var count = rs.boundaries.length; //行政区域的点有多少个
									for (var i = 0; i < count; i++) {
										var ply = new BMap.Polygon(rs.boundaries[i], {
											strokeWeight: 2,
											strokeColor: "#ff0000"
										}); //建立多边形覆盖物
										map.addOverlay(ply); //添加覆盖物
										map.setViewport(ply.getPath()); //调整视野
									}
								});
								console.log(name);
							})
						}
					})
					$("#btn").css("display", "none");
				});
			}
			getBoundary();
		</script>
	</body>
</html>
